#define _CRT_SECURE_NO_WARNINGS

#include "SList.h"
void SLTNode::BuySLTNode(SLTNode*& newnode, Element val)
{
	newnode = (SLTNode*)malloc(sizeof(SLTNode));
	newnode->_next = nullptr;
	newnode->_e = val;
}

void SLTNode::PushFront(Element val, SLTNode*& head)
{
	SLTNode* newnode;
	this->BuySLTNode(newnode, val);
	newnode->_next = head;
	head = newnode;
}

void SLTNode::PushTail(Element val, SLTNode*& head)
{
	SLTNode* newnode;
	this->BuySLTNode(newnode, val);
	if (head == nullptr)
	{
		head = newnode;
		return;
	}
	SLTNode* tem = head;
	while (tem->_next != nullptr)
	{
		tem = tem->_next;
	}
	tem->_next = newnode;
}

void SLTNode::Print()
{
	if (this != nullptr)
	{
		SLTNode* tem = this;
		while (tem != nullptr)
		{
			cout << tem->_e << " ";
			tem = tem->_next;
		}
		cout << endl;
	}
}

void SLTNode::PopBack(SLTNode*& head)
{
	if (this == nullptr) return;
	if (this->_next == nullptr)
	{
		free(this); 
		head = nullptr;
	}
	else 
	{
		SLTNode* tem = this;
		while (tem->_next->_next!=nullptr)
		{
			tem = tem->_next;
		}
		free(tem->_next);
		tem->_next = nullptr;
	}
}

void SLTNode::PopFront(SLTNode*& head)
{
	if (head == nullptr) return;
	SLTNode* tem = head;
	head = head->_next;
	free(tem);
	tem = nullptr;

	//if (head->_next == nullptr)
	//{
	//	free(head);
	//	head = nullptr;
	//}
	//else
	//{
	//	SLTNode* tem = head;
	//	head = head->_next;
	//	free(tem);
	//	tem = nullptr;
	//}
}

SLTNode*& SLTNode::Find(Element val)
{
	SLTNode* p = this;
	while (p != nullptr)
	{
		if (p->_e == val)
			return p;
		p = p->_next;
	}
	p = nullptr;
	return p;
}

void SLTNode::Revise(SLTNode*& p, Element val)
{
	if (p != nullptr)
		p->_e = val;
}

void SLTNode::Insert(Element val, SLTNode* pos, SLTNode*& a)
{
	SLTNode* node;
	pos->BuySLTNode(node, val);
	if (pos == a)
	{
		node->_next = a;
		a = node;
		return;
	}
	SLTNode* p = a;
	while (p->_next != pos)
	{
		p = p->_next;
	}
	node->_next = p->_next;
	p->_next = node;
}

void SLTNode::Erase(SLTNode*& a, SLTNode*& pos)
{
	if (pos == a)
	{
		a = a->_next;
		return;
	}
	while (a->_next != pos)
		a = a->_next;
	a->_next = pos->_next;
}

SLTNode::~SLTNode()
{
	if (this != nullptr)
	{
		SLTNode* tem1 = this;
		while (tem1)
		{
			SLTNode* tem2 = tem1->_next;
			free(tem1);
			tem1 = tem2;
		}
	}
}

